package com.ericzong.renamer.executor.file;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

import org.apache.commons.beanutils.PropertyUtils;

import com.ericzong.renamer.converter.IConverter;
import com.ericzong.renamer.executor.IExecutor;
import com.ericzong.renamer.model.CommonResult;
import com.ericzong.renamer.model.DataSet;
import com.ericzong.renamer.model.Record;

public class FileRenameExecutor implements IExecutor
{
	public void rename( DataSet data )
	{
		CommonResult result = new CommonResult();
		for(Record record : data)
		{
			if(record.getSource().equals(record.getFinalTarget()))
			{
				result.pushNoChange();
				continue;
			}
			
			Path path = null;
			try
			{
				path = (Path) PropertyUtils.getProperty(record, "path");
			}
			catch (Exception e)
			{
				result.pushFail();
				continue;
			}
			
			Path dir = path.getParent();
			try
			{
				Files.move(path, dir.resolve(record.getFinalTarget()));
				result.pushPass();
			}
			catch (IOException e)
			{
				result.pushFail();
			}
		}
		
	}

	@Override
	public void execute(DataSet data, IConverter converter)
	{
		for(Record record : data)
		{
			converter.convert(record);
		}
	}

}
